$(document).ready(function() {
	var VAL ={
        NORMAL : "0000000"  ,
        EVT_USER : $("#userId").text(),
        T_MTPPMITEM : 'MTPPMITEM',
        DISABLED_ATTR : {
            'disabled' : true
        },
        ENABLED_ATTR : {
            'disabled' : false
        }
    };

	var domObj = {
		W : $(window),
			
		$toolRunModeSel : $("#toolRunModeSel"),
		
		$PMItemDialog_titleTxt : $("#PMItemDialog_titleTxt"),
        $PMItemDialog_toolPmNoteTxt : $("#PMItemDialog_toolPmNoteTxt"),
		$PMItemDialog_pmTypeSel : $("#PMItemDialog_pmTypeSel"),
		$PMItemDialog_dataDscTxt : $("#PMItemDialog_dataDscTxt"),
		$PMItemDialog_uSpecTxt : $("#PMItemDialog_uSpecTxt"),
		$PMItemDialog_lSpecTxt : $("#PMItemDialog_lSpecTxt"),
		$PMItemDialog_dataTypeSel : $("#PMItemDialog_dataTypeSel"),
		$PMItemDialog_sampleQtyTxt : $("#PMItemDialog_sampleQtyTxt"),
		
		buttons : {
			$query_btn : $("#query_btn"),
			$import_btn : $("#import_btn"),
			$export_btn : $("#export_btn"),
			$add_btn : $("#add_btn"),
			$save_btn : $("#save_btn"),
            $select_btn : $("#select_btn"),
            $download_btn : $("#download_btn")
		},
		
        grids:{
            $pmItemListDiv : $("#pmItemListDiv"),
            $pmItemListGrd : $("#pmItemListGrd"),
            $pmItemListPg : $("#pmItemListPg")
        }
	};
	
	var controlsFunc={
	   	resizeFunc : function(){ 
	    	comResize(domObj.W, domObj.grids.$pmItemListDiv, domObj.grids.$pmItemListGrd);
	    },
    	iniToolRunModeFunc : function(){//初始化设备运行模式
            comAddValueByDataCateFnc("#toolRunModeSel", "TRMD", "data_ext", "data_desc", true);
    	},
	    /**
    	 * 增加修改和删除按钮
    	 * 说明:(1) addGridButton :在Grid中添加了两个Button: "修改" , "删除"
    	 *     (2) modifyFnc     :点击修改时,调用此函数.
    	 *     (3) deleteFnc     :点击删除时,调用此函数.
    	 */
    	addGridButton : function(){
    		var ids = domObj.grids.$pmItemListGrd.jqGrid('getDataIDs');
    		for(var i=0; i<ids.length; i++){
    			var id=ids[i];   
    			var modify = "<button id=" + "'mod" + ids[i] + "'" + " style='color:#f60'>修改</button>";  
    			var deleteItem = "<button id=" + "'del" + ids[i] + "'" + " style='color:#f60'>删除</button>";  
    			domObj.grids.$pmItemListGrd.jqGrid('setRowData', ids[i], { modifyItem: modify,deleteItem:deleteItem});
    			$("#mod" + ids[i]).click( controlsFunc.modifyFunc );
    			$("#del" + ids[i]).click( controlsFunc.deleteFunc );
    		}  
    	},
    	modifyFunc : function(){
			var tool_model = $.trim(domObj.$toolRunModeSel.val());
			if(!tool_model){
				showErrorDialog("","请选择设备运行模式！");
				return false;
			}
    		controlsFunc.iniDialogFunc("U", tool_model, this.id.substr(3));
    		return false;
    	},
    	deleteFunc : function(){
    		var obj = this ;
            var rowData = domObj.grids.$pmItemListGrd.jqGrid('getRowData', obj.id.substr(3));
            domObj.buttons.$query_btn.showCallBackWarnningDialog({
                errMsg  : "是否删除["+rowData.data_dsc+"]项目,请确认!!!!",
    			callbackFn : function(data) {
    				if(data.result==true){
    					domObj.grids.$pmItemListGrd.jqGrid("delRowData",obj.id.substr(3));
    				}
    			}
    		});
    		return false ;
    	},
    	iniPmTypeFunc : function(){
    		comAddValueByDataCateFnc("#PMItemDialog_pmTypeSel", "PMTP", "ext_1", "data_desc", true);
    		domObj.$PMItemDialog_pmTypeSel.select2({
    			theme : "bootstrap",
    	        width : domObj.W.width()* 0.1755
    	    });
    		domObj.$PMItemDialog_dataTypeSel.select2({
    			theme : "bootstrap",
    	        width : domObj.W.width()* 0.1755
    	    });
    	},
    	iniDialogFunc : function(action_flg, tool_model, id){
		      /*****
	        当多次弹出对话框的同时也会多次绑定click事件。
	        解决办法: 在show Dialog时将click unbind全部掉
	                  然后再绑定，这样就只剩下一个click事件了。
	      **********/
		    $("#PMItemDialog").unbind('shown.bs.modal');
		    $("#PMItemDialog_saveBtn").unbind('click');
		    
    		domObj.$PMItemDialog_titleTxt.text("");
    		$("#PMItemDialog_dataCateForm input").val("");
//    		domObj.$PMItemDialog_toolRunModeTxt.attr(VAL.DISABLED_ATTR);
//    		domObj.$PMItemDialog_toolRunModeTxt.val(tool_model);
    		if(action_flg == "A"){
    			domObj.$PMItemDialog_titleTxt.text("新增保养项目");
    			domObj.$PMItemDialog_pmTypeSel.attr(VAL.ENABLED_ATTR);
    			domObj.$PMItemDialog_dataDscTxt.attr(VAL.ENABLED_ATTR);
    		}else{
    			domObj.$PMItemDialog_titleTxt.text("修改保养项目");
    			domObj.$PMItemDialog_pmTypeSel.attr(VAL.DISABLED_ATTR);
    			domObj.$PMItemDialog_dataDscTxt.attr(VAL.DISABLED_ATTR);
    		}
    		controlsFunc.iniPmTypeFunc();
    		
    		if(action_flg == "U"){
        		var rowData  = domObj.grids.$pmItemListGrd.jqGrid("getRowData",id);
    			domObj.$PMItemDialog_pmTypeSel.val(rowData.pm_type_fk).trigger("change");
    			domObj.$PMItemDialog_dataDscTxt.val(rowData.data_dsc);
    			domObj.$PMItemDialog_uSpecTxt.val(rowData.u_spec);
    			domObj.$PMItemDialog_lSpecTxt.val(rowData.l_spec);
    			domObj.$PMItemDialog_dataTypeSel.val(rowData.data_typ).trigger("change");
    			domObj.$PMItemDialog_sampleQtyTxt.val(rowData.data_cnt);
    			domObj.$PMItemDialog_toolPmNoteTxt.val(rowData.pm_note)

    		}
    		
		    $("#PMItemDialog_saveBtn").bind('click',{action_flg : action_flg, id:id}, btnFunc.dialogSaveFunc);
		    $("#PMItemDialog").modal('show');
    	}
	};
	
	var btnFunc = {
		queryFunc : function(){//查询设备对应的保养设定
			var tool_model = $.trim(domObj.$toolRunModeSel.val());
			if(!tool_model){
				domObj.grids.$pmItemListGrd.jqGrid("clearGridData");
				return false;
			}
			var inTrxObj = {
	            trx_id        : VAL.T_MTPPMITEM ,
	            action_flg    : 'Q'        ,
	            tool_model_fk : tool_model,
	        };
	        
	        var outTrxObj = comTrxSubSendPostJson(inTrxObj);
	        if( outTrxObj.rtn_code == _NORMAL ) {
	        	setGridInfo(outTrxObj.oaryA, "#pmItemListGrd");
	        	controlsFunc.addGridButton();
	        }
		},
        selectFileFunc  :function(){
			var tool_model = $.trim(domObj.$toolRunModeSel.val());
			if(!tool_model){
				showErrorDialog("","请选择设备运行模式！");
				return false;
			}
            domObj.buttons.$select_btn.click();
        },
        uploadFnc : function(obj){
        	//清空jqgrid里面的数据
            domObj.grids.$pmItemListGrd.jqGrid("clearGridData")
            /*
             FileReader共有4种读取方法：
             1.readAsArrayBuffer(file)：将文件读取为ArrayBuffer。
             2.readAsBinaryString(file)：将文件读取为二进制字符串
             3.readAsDataURL(file)：将文件读取为Data URL
             4.readAsText(file, [encoding])：将文件读取为文本，encoding缺省值为'UTF-8'
             */
            var wb;//读取完成的数据
            var rABS = true; //是否将文件读取为二进制字符串
            if(!obj.files) {
                return;
            }
            var fileName = obj.value;
            if(fileName.length > 1 && fileName ) {
                var ldot = fileName.lastIndexOf(".");
                var type = fileName.substring(ldot + 1);
                if(!(type=="xlsx"||type=="xls")) {
                    showErrorDialog("", "只能导入excel文件");
                    return;
                }
            }
            var f = obj.files[0];
            var reader = new FileReader();
            reader.onload = function(e) {
                var data = e.target.result;
                if(rABS) {
                    wb = XLSX.read(btoa(fixdata(data)), {//手动转化
                        type: 'base64'
                    });
                } else {
                    wb = XLSX.read(data, {
                        type: 'binary'
                    });
                }
                //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
                //wb.Sheets[Sheet名]获取第一个Sheet的数据
                var data = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
                data = JSON.parse(JSON.stringify(data).replace(/保养类型/g,"pm_type_fk"));
                data = JSON.parse(JSON.stringify(data).replace(/保养项目名称/g,"data_dsc"));
                data = JSON.parse(JSON.stringify(data).replace(/上规格/g,"u_spec"));
                data = JSON.parse(JSON.stringify(data).replace(/下规格/g,"l_spec"));
                data = JSON.parse(JSON.stringify(data).replace(/数据类型/g,"data_typ"));
                data = JSON.parse(JSON.stringify(data).replace(/样本数量/g,"data_cnt"));
                data = JSON.parse(JSON.stringify(data).replace(/保养描述/g,"pm_note"));
                setGridInfo(data, domObj.grids.$pmItemListGrd);
                controlsFunc.addGridButton();
            };
            if(rABS) {
                reader.readAsArrayBuffer(f);
            } else {
                reader.readAsBinaryString(f);
            }
            function fixdata(data) { //文件流转BinaryString
                var o = "", l = 0, w = 10240;
                for(; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
                o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
                return o;
            }
		},
		exportFunc : function(){
			exportExcel("#pmItemListGrd");
		},
        downloadTempFun: function () {
            if ($("#downForm").length > 0) {
                $("#downForm").remove();
            }
            var str = '<form id="downForm" action="download.do" method="post">';
            str = str + '<input type="hidden" name="fileName" id= "fileName" />';
            str = str + "</form>";
            $(str).appendTo("body");
            $("#fileName").val("3710.xlsx");
            $("#downForm").submit();
        },
		addFunc : function(){
			var tool_model = $.trim(domObj.$toolRunModeSel.val());
			if(!tool_model){
				showErrorDialog("","请选择设备运行模式！");
				return false;
			}
		    controlsFunc.iniDialogFunc("A",tool_model);
		},
		saveFunc : function(){
			var tool_model,
				rowCnt,
				rowIDs,
				rowData,
				iaryA,
				inTrxObj,
	            outTrxObj;
			
			var tool_model = $.trim(domObj.$toolRunModeSel.val());
			if(!tool_model){
				showErrorDialog("","请选择设备运行模式！");
				return false;
			}
			
	        rowCnt = domObj.grids.$pmItemListGrd.jqGrid("getGridParam","reccount");
	        if(rowCnt<=0){
	            showErrorDialog("","保养项目不能为空，请添加保养项目！");
	            return false;
	        }
	        iaryA = new Array();
			rowIDs = domObj.grids.$pmItemListGrd.jqGrid('getDataIDs');
			for(var i=0;i<rowIDs.length;i++){
				rowData = domObj.grids.$pmItemListGrd.jqGrid("getRowData",rowIDs[i]);
				if(!rowData['pm_type_fk']){
					showErrorDialog("","第" + $('#' + rowIDs[i])[0].rowIndex + "行保养类型不能为空！");
					return false;
				}
				
				if(!rowData['data_dsc']){
					showErrorDialog("","第" + $('#' + rowIDs[i])[0].rowIndex + "行保养项目名称不能为空！");
					return false;
				}
				
				if(rowData['u_spec'] && !ComRegex.isNumber(rowData['u_spec'])){
					showErrorDialog("","第" + $('#' + rowIDs[i])[0].rowIndex + "行上规格数值格式不正确！");
					return false;
				}
				if(rowData['l_spec'] && !ComRegex.isNumber(rowData['l_spec'])){
					showErrorDialog("","第" + $('#' + rowIDs[i])[0].rowIndex + "行下规格数值格式不正确！");
					return false;
				}
				
				if(rowData['u_spec'] && rowData['l_spec'] && parseFloat(rowData['u_spec'],10) < parseFloat(rowData['l_spec'],10)){
					showErrorDialog("","第" + $('#' + rowIDs[i])[0].rowIndex + "行上规格不能小于下规格！");
					return false;
				}
				
				if(!rowData['data_typ']){
					showErrorDialog("","第" + $('#' + rowIDs[i])[0].rowIndex + "行数据类型不能为空！");
					return false;
				}
				
				if(!ComRegex.isNumber(rowData['data_cnt'])){
					showErrorDialog("","第" + $('#' + rowIDs[i])[0].rowIndex + "行样本数量数值格式不正确！");
					return false;
				}
                if(!rowData['pm_note']){
                    showErrorDialog("","第" + $('#' + rowIDs[i])[0].rowIndex + "行保养描述不能为空！");
                    return false;
                }

                iaryA.push({
					pm_type_fk  : rowData['pm_type_fk'],
					data_dsc    : rowData['data_dsc'],
					u_spec      : rowData['u_spec'],
					l_spec      : rowData['l_spec'],
					data_typ    : rowData['data_typ'],
                    pm_note     :rowData['pm_note'],
					data_cnt    : parseInt(rowData['data_cnt'],10)
				});
	        }
			
			inTrxObj = {
	            trx_id        : VAL.T_MTPPMITEM ,
	            action_flg    : 'N'        ,
	            evt_user      : VAL.EVT_USER,
	            tool_model_fk : tool_model,
	            iaryA         : iaryA
	        };
	        
	        outTrxObj = comTrxSubSendPostJson(inTrxObj);
	        if(  outTrxObj.rtn_code == _NORMAL ) {
	            showMessengerSuccessDialog("成功保存设定！", 1);
	        }
		},
		dialogSaveFunc : function(e){
			var rowData = new Array();
/*			var tool_model = $.trim(domObj.$PMItemDialog_toolRunModeTxt.val());
			if(!tool_model){
				showErrorDialog("","请选择保养设备运行模式！");
				return false;
			}*/
			
			var pm_type = $.trim(domObj.$PMItemDialog_pmTypeSel.val());
			if(!pm_type){
				showErrorDialog("","请选择保养类型！");
				return false;
			}
			
			var data_dsc = $.trim(domObj.$PMItemDialog_dataDscTxt.val());
			if(!data_dsc){
				showErrorDialog("","请输入保养项目名称！");
				return false;
			}
			//保养描述
			var toolPmNoteTxt = $.trim(domObj.$PMItemDialog_toolPmNoteTxt.val());
			if(!toolPmNoteTxt){
                showErrorDialog("","请输入保养描述！");
                return false;
			}
			
			/**
			 * 检查数据格式
			 */
			var u_spec = $.trim(domObj.$PMItemDialog_uSpecTxt.val());
			if(u_spec && !ComRegex.isNumber(u_spec)){
				showErrorDialog("","上规格不是有效的数字");
				return false;
			}
			var l_spec = $.trim(domObj.$PMItemDialog_lSpecTxt.val());
			if(l_spec && !ComRegex.isNumber(l_spec)){
				showErrorDialog("","下规格不是有效的数字");
				return false;
			}
			
			if(u_spec && l_spec && parseFloat(u_spec,10) < parseFloat(l_spec,10)){
				showErrorDialog("","上规格不能小于下规格");
				return false;
			}
			
			var data_typ = $.trim(domObj.$PMItemDialog_dataTypeSel.val());
			if(!data_typ){
				showErrorDialog("","请选择数据类型！");
				return false;
			}
			var pm_note=$.trim(domObj.$PMItemDialog_toolPmNoteTxt.val());
			var data_cnt = $.trim(domObj.$PMItemDialog_sampleQtyTxt.val());
			if(!data_cnt){
				data_cnt = 1;
			}else if(!ComRegex.isInt(data_cnt)){
				showErrorDialog("","样本数量不是有效的数字");
				return false;
			}
			
			rowData.push({
				pm_type_fk  : pm_type,
				data_dsc    : data_dsc,
				u_spec      : u_spec,
				l_spec      : l_spec,
				data_typ    : data_typ,
                pm_note     : pm_note,
				data_cnt    : parseInt(data_cnt)
			});
			if(e.data.action_flg == "U"){
				domObj.grids.$pmItemListGrd.jqGrid("setRowData", e.data.id, rowData[0]);
			}else{
				//新增时检查保养类型和保养项目是否已经存在
				var rowIDs = domObj.grids.$pmItemListGrd.jqGrid('getDataIDs');
				for(var i=0;i<rowIDs.length;i++){
					var rowdata = domObj.grids.$pmItemListGrd.jqGrid("getRowData",rowIDs[i]);
					if(rowdata['pm_type_fk'] == pm_type && rowdata['data_dsc'] == data_dsc){
						showErrorDialog("","此保养类型、保养项目列表中已经存在，请确认！");
						return false;
					}
		        }
				
				var newRowId = getGridNewRowID("#pmItemListGrd");
				domObj.grids.$pmItemListGrd.jqGrid("addRowData", newRowId, rowData[0]);
				controlsFunc.addGridButton();
			}
			$("#PMItemDialog").modal('hide');
		}
	};

  
    function iniGridInfo() {
    	var measureItemListInfoCM = [
    	    {name: 'modifyItem'   , index: 'modifyItem'    , label: MODIFY_BTN_TAG,     sortable: false  ,width: 80 },
     	    {name: 'deleteItem'   , index: 'deleteItem'    , label: DELETE_BTN_TAG , sortable: false  ,width: 80 },
     	    {name: 'pm_type_fk'      , index: 'pm_type_fk'     , label: "保养类型"       , sortable: false  ,width: 170 },
     	    {name: 'data_dsc'        , index: 'data_dsc'       , label: "保养项目名称"     , sortable: false  ,width: 330 },
     	    {name: 'u_spec'          , index: 'u_spec'         , label: "上规格"         , sortable: false  ,width: 170 },
     	    {name: 'l_spec'          , index: 'l_spec'         , label: "下规格"         , sortable: false  ,width: 170 },
     	    {name: 'data_typ'        , index: 'data_typ'       , label: "数据类型"        , sortable: false  ,width: 170 },
     	    {name: 'data_cnt'        , index: 'data_cnt'       , label: "样本数量"        , sortable: false  ,width: 150 },
            {name: 'pm_note'        , index: 'pm_note'       , label: "保养描述"        , sortable: false  ,width: 150 }
     	];
     	domObj.grids.$pmItemListGrd.jqGrid({
     		  url:"",
     	      datatype:"local",
     	      mtype:"POST",
     	      autowidth:true,//宽度根据父元素自适应
            shrinkToFit:false,
            autoScroll: false,
     	      scroll:false,
     	      resizable : true,
     	      loadonce:true,
     	      fixed: true,
     	      viewrecords : true, //显示总记录数
     	      pager : '#pmItemListPg',
     	      rownumbers  :true ,//显示行号
     	      pginput  : false ,
     	      rownumWidth : 20,  //行号列宽度
     	      emptyrecords :true ,
     	      colModel: measureItemListInfoCM
     	});
    }
    
    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
    	controlsFunc.resizeFunc();
    	controlsFunc.iniToolRunModeFunc();
    };
    
    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
    	domObj.buttons.$query_btn.click(function(){
    		btnFunc.queryFunc();
    	});
    	
    	domObj.buttons.$import_btn.click(function(){
    		btnFunc.selectFileFunc();
    	});
    	
    	domObj.buttons.$export_btn.click(function(){
    		btnFunc.exportFunc();
    	});
    	
    	domObj.buttons.$add_btn.click(function(){
    		btnFunc.addFunc();
    	});
    	
    	domObj.buttons.$save_btn.click(function(){
    		btnFunc.saveFunc()
    	});
    	
        domObj.buttons.$select_btn.change(function() {
            btnFunc.uploadFnc(this);
        });
        
        domObj.buttons.$download_btn.click(function(){
            btnFunc.downloadTempFun();
        });
    };
    
    /**
     * Other action bind
     */
    var otherActionBind = function(){
	    $("form").submit(function(){
	        return false;
	    });
	    
	    domObj.W.resize(function() {
	    	controlsFunc.resizeFunc();
    	});
        
	    domObj.$toolRunModeSel.change(function(){
            btnFunc.queryFunc();
	    });
	    
    };

    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
    	iniGridInfo();
    	iniContorlData();
    	iniButtonAction();
    	otherActionBind();
    };
    
    initializationFunc();
    //表格自适应
    function resizeFnc(){
        var offsetBottom, divWidth;
        divWidth = $("#pmItemListDiv").width();
        offsetBottom =  $(window).height() - $("#pmItemListDiv").offset().top;
        $("#pmItemListDiv").height(offsetBottom * 0.95);
        $("#pmItemListGrd").setGridWidth(divWidth * 0.85);
        $("#pmItemListGrd").setGridHeight(offsetBottom * 0.99 - 51);

    };
    resizeFnc();
    $(window).resize(function() {
        resizeFnc();
    });
});